<?php

namespace App\Services;

use App\Model\Normal;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Utils\ApplicationContext;
use GuzzleHttp\Client;
use AopCertClient;
use AlipayConfig;

class AlipayService
{
    private static $aopClient;

    // 初始化证书客户端
    private static function initAopClient()
    {
        if (!self::$aopClient) {
            $config = new AlipayConfig();
            $config->setServerUrl("https://openapi.alipay.com/gateway.do");
            $config->setAppId(config('alipay.appid'));
            $config->setPrivateKey(config('alipay.private_key'));
            $config->setAppCertPath(BASE_PATH . '/storage/alipay/appCertPublicKey_2021004189634756.crt');
            $config->setAlipayPublicCertPath(BASE_PATH . '/storage/alipay/alipayCertPublicKey_RSA2.crt');
            $config->setRootCertPath(BASE_PATH . '/storage/alipay/alipayRootCert.crt');
            $config->setCharset('UTF-8');
            $config->setSignType('RSA2');

            self::$aopClient = new AopCertClient($config);
        }
        return self::$aopClient;
    }

    public static function getUserId($code)
    {
        try {
            $aop = self::initAopClient();
            $request = new \AlipaySystemOauthTokenRequest();
            $request->setCode($code);
            $request->setGrantType('authorization_code');

            $response = $aop->execute($request);

            // 调试日志
            Normal::logger('Alipay Response: ' . json_encode($response), 'order-queue');
            return (array) $response->alipay_system_oauth_token_response;
        } catch (\Exception $e) {
            Normal::logger('支付宝授权异常: ' . $e->getMessage().$e->getTraceAsString(), 'order-queue');
            return ['error' => $e->getMessage()];
        }
    }

    public static function getRedirect($sn)
    {
        try {
            $aop = self::initAopClient();
            $request = new \AlipayOpenMiniQrcodeBindRequest();
            $bizContent = [
                'mode' => 'FUZZY',
                'page_redirection' => 'pages/home/index?sn=' . $sn,
                'route_url' => 'https://www.chdyzw.com/'
            ];
            $request->setBizContent(json_encode($bizContent));

            $response = $aop->execute($request);


            return (array)$response;
        } catch (\Exception $e) {
            Normal::logger('生成二维码异常: ' . $e->getMessage(), 'alipay-error');
            return ['error' => $e->getMessage()];
        }
    }

    // 保留必要的辅助方法
    private static function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            return mb_convert_encoding($data, $targetCharset, 'UTF-8');
        }
        return $data;
    }

    // 保留HTTP客户端方法
    public static function aliPost($url, $data, $type = 'form_params', $charset = 'UTF-8')
    {
        $container = ApplicationContext::getContainer();
        $handlerStackFactory = $container->get(HandlerStackFactory::class);
        $handlerStack = $handlerStackFactory->create();
        $client = new Client(['handler' => new CoroutineHandler($handlerStack)]);

        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded;charset='.$charset,
            ],
            $type => $data
        ]);

        return $response->getBody()->getContents();
    }
}